import ctypes

if '__main__' == __name__:

    xdata = [
        [1, 2],
        [8, 9],
        [8, 7],
        [10, -1],
        [5, 6],
        [3, 4],
        [5, 4]
    ]

    num2set_map = dict()

    for xpair in xdata:
        x, y = xpair
        print('>>>', x, y)

        set_x = num2set_map.get(x, None)
        set_y = num2set_map.get(y, None)

        if -1 == x and -1 == y:
            continue
        elif -1 == y:
            if set_x is not None:
                continue
            else:
                print(x, '->', 'set(', x, ')')
                num2set_map[x] = set([x])
                continue
        elif -1 == x:
            if set_y is not None:
                continue
            else:
                print(y, '->', 'set(', y, ')')
                num2set_map[y] = set([y])
                continue

        # -1 != x and -1 != y

        if set_x is None and set_y is None:
            print(x, '-> set(', x, y, ')')
            print(y, '-> set(', x, y, ')')
            set_xy = set([x, y])
            num2set_map[y] = set_xy
            num2set_map[x] = set_xy
            continue
        elif set_y is None:
            set_x.add(y)
            print(y, '-> ', set_x)
            num2set_map[y] = set_x
            continue
        elif set_x is None:
            set_y.add(x)
            print(x, '-> ', set_y)
            num2set_map[x] = set_y
            continue
        else:
            if set_x == set_y:  # already associated
                print(x, y, 'already associated')
                continue
            else:
                print(set_x, 'union', set_y)
                set_xy = set_x.union(set_y)
                print('=>', set_xy)
                for xnum in set_xy:
                    print(xnum, '->', set_xy)
                    num2set_map[xnum] = set_xy

    print('Result')
    xsets_ids = set()
    for xset in num2set_map.values():
        # xsets.add(tuple(sorted(list(xset))))
        xsets_ids.add(id(xset))

    xsets = []
    for xid in xsets_ids:
        # https://stackoverflow.com/questions/1396668/get-object-by-id
        xset = ctypes.cast(xid, ctypes.py_object).value
        print('from ctypes:', xset)
        xsets.append(tuple(xset))

    xresult = sorted(xsets)
    for xtup in xresult:
        print(xtup)
